<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Back, VideoPlay } from '@element-plus/icons-vue'
import { detectAndRecognizeImage, getFullStaticUrl } from '@/api'
import { useImageStore } from '@/stores/image'
import { useRouter } from 'vue-router'

const router = useRouter()
const imageStore = useImageStore()
const loadingDetect = ref(false)

// 模型选择
const selectedModel = ref<'model_a' | 'model_b' | 'model_c' | 'model_d'>('model_b')
const modelOptions = [
  { value: 'model_a' as const, label: '车辆检测模型', description: '仅检测车辆位置' },
  { value: 'model_b' as const, label: '车牌识别模型', description: '同时检测车辆与车牌' },
  { value: 'model_c' as const, label: '车辆-车牌联合检测模型', description: '联合检测车辆与车牌' },
  { value: 'model_d' as const, label: '多辆车检测模型', description: '同时检测多辆车辆' }
]

const preprocessedImageUrl = computed(() => {
  if (!imageStore.preprocessedImage) return ''
  const url = getFullStaticUrl(imageStore.preprocessedImage)
  console.log('预处理图片URL:', url)
  return url
})

// 计算属性
const canDetect = computed(() => {
  return !!imageStore.preprocessedImage && !loadingDetect.value && !!selectedModel.value
})

const handleDetectAndRecognize = async () => {
  if (!imageStore.preprocessedImage) {
    ElMessage.warning('请先上传并预处理图片')
    return
  }
  
  loadingDetect.value = true
  try {
    console.log('开始检测识别，图片URL:', imageStore.preprocessedImage)
    console.log('预处理图片路径:', imageStore.preprocessedImagePath)
    console.log('选择的模型:', selectedModel.value)
    
    // 优先使用图片路径进行检测
    const imagePath = imageStore.preprocessedImagePath || imageStore.preprocessedImage
    const res = await detectAndRecognizeImage(imagePath, selectedModel.value)
    
    console.log('检测识别结果:', res)
    
    if (res && res.marked_image_url) {
      imageStore.setDetectionResult(res)
      ElMessage.success('检测识别完成')
      router.push('/result')
    } else {
      throw new Error('检测响应格式不正确')
    }
  } catch (e: any) {
    console.error('检测错误详情:', e)
    const errorMsg = e.response?.data?.error || e.message || '检测识别失败'
    ElMessage.error(errorMsg)
  } finally {
    loadingDetect.value = false
  }
}
</script>

<template>
  <div class="preprocess-view">
    <div class="page-header">
      <h2>预处理检测</h2>
      <p class="subtitle">选择检测模型并开始分析</p>
    </div>

    <el-card class="section-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>预处理结果</span>
          <el-button type="primary" link @click="$router.push('/upload')">
            <el-icon><Back /></el-icon>
            返回上传
          </el-button>
        </div>
      </template>
      
      <template v-if="imageStore.preprocessedImage">
        <div class="image-section">
          <div class="image-wrapper">
            <el-image :src="preprocessedImageUrl" fit="contain" class="preview-img" @error="(e: Event) => console.error('预处理图片加载错误:', preprocessedImageUrl, e)">
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                  <div>URL: {{ preprocessedImageUrl }}</div>
                </div>
              </template>
            </el-image>
            <div class="image-overlay">
              <el-tag type="success">预处理完成</el-tag>
            </div>
          </div>
        </div>

        <div class="model-section">
          <h3 class="section-title">选择检测模型</h3>
          <div class="model-cards">
            <el-radio-group v-model="selectedModel" class="model-group">
              <div
                v-for="option in modelOptions"
                :key="option.value"
                class="model-card"
                :class="{ 'is-selected': selectedModel === option.value }"
                @click="selectedModel = option.value"
              >
                <div class="model-icon">
                  <el-icon :size="32">
                    <component :is="option.value === 'model_a' ? 'Van' : option.value === 'model_b' ? 'Guide' : option.value === 'model_c' ? 'Car' : 'Group'" />
                  </el-icon>
                </div>
                <div class="model-info">
                  <h4>{{ option.label }}</h4>
                  <p>{{ option.description }}</p>
                </div>
                <el-radio :label="option.value" class="model-radio" />
              </div>
            </el-radio-group>
          </div>
        </div>

        <div class="action-section">
          <el-button
            type="primary"
            class="action-btn"
            :loading="loadingDetect"
            :disabled="!canDetect"
            @click="handleDetectAndRecognize"
          >
            <el-icon><VideoPlay /></el-icon>
            开始检测识别
          </el-button>
          <p class="help-text" v-if="!loadingDetect">
            选择合适的模型后点击"开始检测识别"
          </p>
        </div>
      </template>

      <el-empty
        v-else
        class="image-empty"
        description="请先上传并预处理图片"
      >
        <template #image>
          <el-icon :size="48" color="#909399"><Picture /></el-icon>
        </template>
        <template #default>
          <el-button type="primary" @click="$router.push('/upload')">
            去上传图片
          </el-button>
        </template>
      </el-empty>
    </el-card>
  </div>
</template>

<style scoped>
.preprocess-view {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.page-header {
  margin-bottom: 8px;
}

.page-header h2 {
  font-size: 1.8rem;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 8px;
}

.subtitle {
  color: #606266;
  font-size: 1rem;
}

.section-card {
  flex: 1;
  background: #fff;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all var(--transition-speed);
}

.section-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.card-header span {
  font-size: 1.1rem;
  font-weight: 500;
  color: var(--text-color);
}

.image-section {
  margin-bottom: 32px;
}

.image-wrapper {
  position: relative;
  border-radius: var(--border-radius);
  overflow: hidden;
}

.preview-img {
  width: 100%;
  height: 300px;
  object-fit: contain;
  background: #f8fafc;
  border: 1px solid #ebeef5;
}

.image-overlay {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 1;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  gap: 8px;
}

.section-title {
  font-size: 1.1rem;
  font-weight: 500;
  color: var(--text-color);
  margin-bottom: 16px;
}

.model-section {
  padding: 24px 0;
  border-top: 1px dashed #dcdfe6;
}

.model-cards {
  margin: 0 -8px;
}

.model-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  width: 100%;
}

.model-card {
  position: relative;
  padding: 20px;
  border: 2px solid #ebeef5;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all var(--transition-speed);
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.model-card:hover {
  border-color: var(--primary-color);
  background: var(--primary-light);
}

.model-card.is-selected {
  border-color: var(--primary-color);
  background: var(--primary-light);
}

.model-icon {
  padding: 12px;
  background: #fff;
  border-radius: var(--border-radius);
  color: var(--primary-color);
}

.model-info {
  flex: 1;
}

.model-info h4 {
  font-size: 1rem;
  font-weight: 500;
  color: var(--text-color);
  margin: 0 0 8px;
}

.model-info p {
  font-size: 0.9rem;
  color: #606266;
  margin: 0;
}

.model-radio {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
}

.action-section {
  text-align: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px dashed #dcdfe6;
}

.action-btn {
  min-width: 180px;
  height: 44px;
  font-size: 1rem;
}

.help-text {
  margin-top: 12px;
  color: #909399;
  font-size: 0.9rem;
}

.image-empty {
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f8fafc;
  border-radius: var(--border-radius);
  border: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .preprocess-view {
    padding: 16px;
    gap: 16px;
  }

  .page-header h2 {
    font-size: 1.5rem;
  }

  .preview-img {
    height: 240px;
  }

  .model-group {
    grid-template-columns: 1fr;
  }

  .action-btn {
    width: 100%;
  }
}
</style> 